package com.ruoyi.merchant.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.merchant.domain.MerchantDishAudit;
import com.ruoyi.merchant.domain.Product;
import com.ruoyi.merchant.domain.ProductSpecDetail;
import com.ruoyi.merchant.domain.ProductSpecGroup;
import com.ruoyi.merchant.domain.dto.DishDetailUpdateDTO;
import com.ruoyi.merchant.domain.dto.DishSubmitDTO;

import com.ruoyi.merchant.domain.dto.SkuDTO;
import com.ruoyi.merchant.domain.dto.SkuPriceStockUpdateDTO;

import com.ruoyi.merchant.mapper.MerchantDishAuditMapper;
import com.ruoyi.merchant.mapper.ProductMapper;
import com.ruoyi.merchant.mapper.ProductSpecDetailMapper;
import com.ruoyi.merchant.mapper.ProductSpecGroupMapper;
import com.ruoyi.merchant.service.IMerchantDishAuditService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜品审核Service业务层处理
 */
@Service
public class MerchantDishAuditServiceImpl implements IMerchantDishAuditService {

    @Autowired
    private MerchantDishAuditMapper merchantDishAuditMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSpecGroupMapper specGroupMapper;

    @Autowired
    private ProductSpecDetailMapper specDetailMapper;

    @Override
    public MerchantDishAudit selectDishAuditByAuditId(Long auditId) {
        MerchantDishAudit audit = merchantDishAuditMapper.selectDishAuditByAuditId(auditId);
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (audit != null && !merchantId.equals(audit.getMerchantId())) {
            throw new ServiceException("无权访问该审核记录");
        }
        return audit;
    }

    @Override
    public List<MerchantDishAudit> selectDishAuditList(MerchantDishAudit merchantDishAudit) {
        merchantDishAudit.setMerchantId(MerchantSecurityUtils.getMerchantId());
        return merchantDishAuditMapper.selectDishAuditList(merchantDishAudit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitNewDish(DishSubmitDTO dishSubmitDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 1. 构建审核记录
        MerchantDishAudit audit = new MerchantDishAudit();
        audit.setMerchantId(merchantId);
        audit.setDishName(dishSubmitDTO.getDishName());
        audit.setCategoryId(dishSubmitDTO.getCategoryId());
        audit.setDescription(dishSubmitDTO.getDescription());
        audit.setImageUrl(dishSubmitDTO.getImageUrl());
        audit.setDishTags(dishSubmitDTO.getDishTags());
        audit.setIsRecommended(dishSubmitDTO.getIsRecommended());
        audit.setAuditStatus("0"); // 待审核
        audit.setApplicationTime(new Date());
        audit.setDishStatus("1"); // 默认在售
        audit.setSalesCount(0);
        audit.setCreateBy(SecurityUtils.getUsername());

        // 2. 将规格信息转为JSON存储
        Map<String, Object> specsData = new HashMap<>();
        specsData.put("specGroups", dishSubmitDTO.getSpecGroups());
        specsData.put("skuList", dishSubmitDTO.getSkuList());
        audit.setDishSpecs(JSON.toJSONString(specsData));

        // 3. 计算总库存和基础价格
        int totalStock = 0;
        BigDecimal minPrice = null;
        for (SkuDTO sku : dishSubmitDTO.getSkuList()) {
            totalStock += sku.getStock();
            if (minPrice == null || sku.getPrice().compareTo(minPrice) < 0) {
                minPrice = sku.getPrice();
            }
        }
        audit.setStockQuantity(totalStock);
        audit.setPrice(minPrice); // 使用最低价作为展示价格

        // 4. 保存审核记录
        int result = merchantDishAuditMapper.insertDishAudit(audit);

        if (result > 0) {
            return result;
        }
        throw new ServiceException("提交审核失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitDishUpdate(DishDetailUpdateDTO dishDetailUpdateDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Long dishId = dishDetailUpdateDTO.getDishId();

        // 1. 验证菜品是否存在且属于当前商家
        Product product = productMapper.selectProductByProductId(dishId);
        if (product == null) {
            throw new ServiceException("菜品不存在");
        }
        if (!merchantId.equals(product.getMerchantId())) {
            throw new ServiceException("无权修改该菜品");
        }

        // 2. 查询现有规格信息
        List<ProductSpecGroup> specGroups = specGroupMapper.selectByProductId(dishId);
        List<ProductSpecDetail> skuList = specDetailMapper.selectByProductId(dishId);

        // 3. 构建审核记录
        MerchantDishAudit audit = new MerchantDishAudit();
        audit.setMerchantId(merchantId);
        audit.setDishId(dishId);
        audit.setDishName(dishDetailUpdateDTO.getDishName());
        audit.setCategoryId(dishDetailUpdateDTO.getCategoryId());
        audit.setDescription(dishDetailUpdateDTO.getDescription());
        audit.setImageUrl(dishDetailUpdateDTO.getImageUrl());
        audit.setDishTags(dishDetailUpdateDTO.getDishTags());
        audit.setIsRecommended(dishDetailUpdateDTO.getIsRecommended());
        audit.setAuditStatus("0"); // 待审核
        audit.setApplicationTime(new Date());
        audit.setCreateBy(SecurityUtils.getUsername());

        // 4. 保存现有规格信息到JSON
        Map<String, Object> specsData = new HashMap<>();
        specsData.put("specGroups", specGroups);
        specsData.put("skuList", skuList);
        audit.setDishSpecs(JSON.toJSONString(specsData));

        // 5. 计算价格和库存
        int totalStock = 0;
        BigDecimal minPrice = null;
        for (ProductSpecDetail sku : skuList) {
            totalStock += sku.getStock();
            if (minPrice == null || sku.getPrice().compareTo(minPrice) < 0) {
                minPrice = sku.getPrice();
            }
        }
        audit.setStockQuantity(totalStock);
        audit.setPrice(minPrice);
        audit.setDishStatus(product.getStatus().toString());
        audit.setSalesCount(product.getSalesCount());

        // 6. 保存审核记录
        int result = merchantDishAuditMapper.insertDishAudit(audit);

        // 7. 更新商品状态为待审核
        Product updateProduct = new Product();
        updateProduct.setProductId(dishId);
        updateProduct.setAuditStatus(0); // 待审核
        updateProduct.setStatus(0); // 自动下架
        productMapper.updateProduct(updateProduct);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSkuPriceAndStock(SkuPriceStockUpdateDTO dto) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 1. 验证SKU是否存在
        ProductSpecDetail sku = specDetailMapper.selectBySkuId(dto.getSkuId());
        if (sku == null) {
            throw new ServiceException("SKU不存在");
        }

        // 2. 查询SKU所属的商品
        Long productId = specDetailMapper.selectProductIdBySkuId(dto.getSkuId());
        Product product = productMapper.selectProductByProductId(productId);
        if (product == null || !merchantId.equals(product.getMerchantId())) {
            throw new ServiceException("无权修改该SKU");
        }

        // 3. 更新SKU价格和库存
        ProductSpecDetail updateSku = new ProductSpecDetail();
        updateSku.setSkuId(dto.getSkuId());
        updateSku.setPrice(dto.getPrice());
        updateSku.setStock(dto.getStock());
        updateSku.setMarketPrice(dto.getMarketPrice());

        int result = specDetailMapper.updatePriceAndStock(updateSku);

        // 4. 更新商品总库存（可选）
        if (result > 0) {
            List<ProductSpecDetail> allSkus = specDetailMapper.selectByProductId(productId);
            int totalStock = allSkus.stream().mapToInt(ProductSpecDetail::getStock).sum();
            
            Product updateProduct = new Product();
            updateProduct.setProductId(productId);
            updateProduct.setStockQuantity(totalStock);
            productMapper.updateProduct(updateProduct);
        }

        return result;
    }

    @Override
    public List<MerchantDishAudit> selectPendingAuditList() {
        return merchantDishAuditMapper.selectPendingAuditList(MerchantSecurityUtils.getMerchantId());
    }

    @Override
    public MerchantDishAudit selectLatestAuditByDishId(Long dishId) {
        return merchantDishAuditMapper.selectLatestAuditByDishId(dishId);
    }
}
